﻿using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using NHibernate;
using TimeKeeper.Entities;
using TimeKeeper.Infrastructure;

namespace TimeKeeper.Validators
{
    public class ProjectValidator : AbstractValidator<Project>
    {
        private readonly IStatelessSession _session;

        public ProjectValidator(IStatelessSession session)
        {
            _session = session;
            
            RuleFor(x => x.Name)
                .NotEmpty()
                .Must((project, name) =>
                          {
                              var result = false;
                              _session.QueryInTransaction<Project>(q => result = q.Count(x => x.Id != project.Id && x.Name == project.Name) == 0);
                              return result;
                          })
                .WithMessage("'{PropertyName}' is already taken.");

            RuleFor(x => x.Description).NotEmpty();
        }
    }
}
